import React, {useState} from 'react';
import {
  useSetState,
  useMount,
  useUpdateEffect,
  useDebounceEffect,
  useSafeState,
} from 'ahooks';
import dayjs from 'dayjs';
import {View, StyleSheet} from 'react-native';
import {Skeleton, Text, Button} from '@rneui/base';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {useSelector, useDispatch} from 'react-redux';
import RNDI from 'react-native-device-info';
import {setAccountInfo, setToken, setDeviceInfo} from '@/store';
import {ApiHost} from '@/config/common';
export default ({children}) => {
  const dispatch = useDispatch();
  const routeData = useSelector(state => state.routeData.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  const isSignedIn = !!accountInfo?.account_id;
  const keyGetAccountInfo = useSelector(state => state.keyGetAccountInfo.value);
  const deviceInfo = useSelector(state => state.deviceInfo.value);
  useMount(async () => {
    dispatch(
      setDeviceInfo({
        uniqueId: await RNDI.getUniqueId(),
      }),
    );
  });
  const [loading, setLoading] = useSafeState();
  useDebounceEffect(
    () => {
      (async () => {
        try {
          const oldToken = await AsyncStorage.getItem('token');
          let oldTokenInfo = JSON.parse(
            await AsyncStorage.getItem('tokenInfo'),
          );
          let oldAccountInfo = JSON.parse(
            await AsyncStorage.getItem('accountInfo'),
          );
          const surplusDays = dayjs(oldTokenInfo.exp_str).diff(dayjs(), 'days');
          const surplusH = dayjs(oldTokenInfo.exp_str)
            .subtract(surplusDays, 'd')
            .diff(dayjs(), 'h');
          const surplusMinutes = dayjs(oldTokenInfo.exp_str)
            .subtract(surplusDays, 'd')
            .subtract(surplusH, 'h')
            .diff(dayjs(), 'minutes');

          const surplusSec = dayjs(oldTokenInfo.exp_str)
            .subtract(surplusDays, 'd')
            .subtract(surplusH, 'h')
            .subtract(surplusMinutes, 'minute')
            .diff(dayjs(), 'second');
          console.log(
            `距token过期还剩下${surplusDays}天,${surplusH}时,${surplusMinutes}分,${surplusSec}秒`,
          );

          const updateToken = async () => {
            let rsObj = undefined;
            try {
              const reqFormData = {};
              let res = await fetch(`${ApiHost}/account/json/login-by-token`, {
                headers: {
                  'content-type': 'application/json',
                  token: oldToken,
                },
                method: 'POST',
                body: JSON.stringify(reqFormData),
              });
              rsObj = await res.json();
            } catch (e) {}
            const {
              code,
              msg,
              account_info,
              token,
              token_info = {},
            } = rsObj || {};
            // console.log('account_info', account_info);
            if (code >= 1) {
              AsyncStorage.setItem('token', token);
              AsyncStorage.setItem('tokenInfo', JSON.stringify(token_info));
              AsyncStorage.setItem('accountInfo', JSON.stringify(account_info));
              dispatch(setAccountInfo(account_info));
              dispatch(setToken(token));
            } else {
              AsyncStorage.removeItem('token');
              AsyncStorage.removeItem('tokenInfo');
              AsyncStorage.removeItem('accountInfo');
              dispatch(setAccountInfo({}));
              dispatch(setToken(''));
            }
          };

          if (surplusDays > 1) {
            dispatch(setAccountInfo(oldAccountInfo));
            dispatch(setToken(oldToken));
            updateToken();
          } else {
            setLoading(true);
            await updateToken();
          }
        } catch (e) {
          AsyncStorage.removeItem('token');
          AsyncStorage.removeItem('tokenInfo');
          AsyncStorage.removeItem('accountInfo');
          dispatch(setAccountInfo({}));
          dispatch(setToken(''));
          console.log('获取登录信息异常', e.message);
        }
        setLoading(false);
      })();
    },
    [keyGetAccountInfo],
    {wait: 0},
  );
  if (loading === undefined) {
    return <></>;
  }
  if (!deviceInfo?.uniqueId) {
    return (
      <>
        <Text>!uniqueId</Text>
      </>
    );
  }
  if (loading) {
    return (
      <>
        <View style={style.box}>
          {new Array(5).fill().map((item, index) => (
            <View key={index} style={style.list}>
              <Skeleton animation="wave" width={120} height={40} />
              <Skeleton circle width={40} height={40} />
              <Skeleton circle width={40} height={40} />
            </View>
          ))}
          <View style={style.txtBox}>
            <Text h4 style={style.txtInit}>
              init data ……
            </Text>
            <Button type="clear" disabled loading />
          </View>
        </View>
      </>
    );
  }
  return children;
};
const style = StyleSheet.create({
  box: {
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  list: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 10,
  },
  txtBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10,
  },
  txtInit: {
    color: '#ccc',
  },
});
